package cn.wmlce.web.ch4_6;

import cn.wmlce.MyMvcConfig;
import cn.wmlce.service.DemoService;
import org.junit.Before;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.mock.web.MockHttpSession;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.junit.runner.RunWith;
import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.request.async.DeferredResult;

import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = {MyMvcConfig.class})
@WebAppConfiguration("src/main/resources") //1@WebAppConfiguration注解在类上，用来声明加载的ApplicationContext是WebApplicationContext,它的属性指的是Web资源的位置
public class TestControllerIntegrationTests {
    private MockMvc mockMvc;//2MockMvc-模拟MVC对象，通过MockMvcBuilders.webAppContextSetup(this.wac).build()初始化

    @Autowired
    private DemoService demoService;//可以在测试用例中注入Spring的Bean

    @Autowired
    WebApplicationContext wac;//4可注入WebApplicationContext

    @Autowired
    MockHttpSession mockHttpSession;//5可注入模拟的http Session

    @Autowired
    MockHttpServletRequest request;//6可以注入http request

    @Before//7在测试开始之前进行初始化工作
    public void setup(){
        this.mockMvc = MockMvcBuilders.webAppContextSetup(this.wac).build();//2
    }

    @Test
    public void testNormalController() throws Exception{
        mockMvc.perform(get("normal")) //模拟向/normal进行get请求
                .andExpect(status().isOk()) //预期控制返回状态为200
                .andExpect(view().name("page")) //预期view的名称为page
                .andExpect(forwardedUrl("/WEB-INF/classes/views/page.jsp"))//预期页面转向的真正路径为/WEB-INF/classes/views/page.jsp
                .andExpect(model().attribute("msg",demoService.saySomething()));//预期model里的值是demoService.saySomething()返回值hello
    }

    @Test
    public void testRestController() throws Exception{
        mockMvc.perform(get("testRest"))//模拟向/testRest进行get请求
                .andExpect(status().isOk())
                .andExpect(content().contentType("text/plain;charset=UTF-8"))//预期返回值的媒体类型为text/plain;charset=UTF-8
                .andExpect(content().string(demoService.saySomething()));//预期返回值的内容为demoService.saySomething()
    }
}
